layui.use(['form','layer','laydate','table','laytpl','element'],function() {
    var element = layui.element;
    var laydate = layui.laydate;
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;
    var currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
    var targetCallPhone = localStorage.getItem("targetCallPhone");//将号码和localStorage

    //添加话术包
    form.on('submit(add)', function(formData){
        //弹出loading
        var load = layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});
        var submitData = formData.field;
        var bo = verification(formData.form,null);
        if(bo) {
            saveData(submitData, load);
        }else{
            layer.close(load);
        }
    });

    function saveData(submitData,load) {
        layer.close(load);
        var regTxt =/^([0-9]{3,4}-)?[0-9]{7,8}$/ ;
        var regTelPhoneTxt =/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        if(submitData["mainPhone"]!="" && !regTxt.test(submitData["mainPhone"]) && !regTelPhoneTxt.test(submitData["mainPhone"])){
            layer.msg("请输入正确的客户号码（格式：手机号码或固话）", {
                icon: 5
                , shift: 6
            });
        }else if(submitData["targetPhone"]!="" && !regTxt.test(submitData["targetPhone"]) && !regTelPhoneTxt.test(submitData["targetPhone"])){
            layer.msg("请输入正确call客号码（格式：手机号码或固话）", {
                icon: 5
                , shift: 6
            });
        }else if(submitData["mainPhone"] == submitData["targetPhone"]){
            layer.msg("被叫号码和主叫号码不能相同", {
                icon: 5
                , shift: 6
            });
        }else{
            parent.setPhone(submitData["mainPhone"],submitData["targetPhone"]);


            //freeswitch用户注册
            // parent.initSIPUA();

            //iframe中跨域通信
          /*  function postMessage(data){
                var post = {method:"setPhone",mainPhone:submitData["mainPhone"],targetPhone:submitData["targetPhone"]};
                window.parent.postMessage(post,'*');
            }*/
            layer.msg("保存成功！");
            $("#cancel").click();
        }
    }

    //验证表单
    function verification(form,iframeWin) {
        var config = {
            verify: {
                required: [
                    /[\S]+/
                    , '必填项不能为空'
                ]
                , phone: [
                    /^([0-9]{3,4}-)?[0-9]{7,8}$/
                    , '请输入正确的手机号或固话号码'
                ],
                telphone:[
                    /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/
                    ,'请输入正确的手机号或固话号码'
                ]
                , email: [
                    /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$|^$/
                    , '邮箱格式不正确'
                ]
                , url: [
                    /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/
                    , '链接格式不正确'
                ]
                , number: [
                    /^\d+$|^$/
                    , '只能填写数字'
                ]
                , date: [
                    /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$|^$/
                    , '日期格式不正确'
                ]
                , identity: [
                    /(^\d{15}$)|(^\d{17}(x|X|\d)$|^$)/
                    , '请输入正确的身份证号'
                ]
            }
        };
        formElem = $(form);
        var button = $(this), verify = config.verify, stop = null
            , DANGER = 'layui-form-danger',PROMPT='required_prompt', field = {}
            , verifyElem = formElem.find('*[lay-verify-zdy]') //获取需要校验的元素
            //, fieldElem = formElem.find('input,select,textarea') //获取所有表单域
            , checkedElem = formElem.find('*[data-required]') //获取复选框
            ,rangeElem = formElem.find('*[data-range]')//获取范围判断的区间值

        //开始校验
        layui.each(verifyElem, function (_, item) {
            var othis = $(this), tips = '';
            var arr = othis.attr('lay-verify-zdy').split(',');
            for (var i in arr) {
                var ver = arr[i];
                var value = othis.val(), isFn = typeof verify[ver] === 'function';
                if(ver == 'number'&&value==''){
                    value = 0;
                }
                othis.removeClass(DANGER);
                if (verify[ver] && (isFn ? tips = verify[ver](value, item) :  ver=="phone"?!verify[ver][0].test(value)&&!verify["telphone"][0].test(value):!verify[ver][0].test(value))) {
                    layer.msg(tips || verify[ver][1], {
                        icon: 5
                        , shift: 6
                    });
                    //非移动设备自动定位焦点
                    if (!layui.device().android && !layui.device().ios) {
                        if(item.type=='text'){
                            item.focus();
                        }else if(item.type=="select-one"){
                            $(item).next("div").find("input").focus();
                            $(item).next("div").find("input").attr("readonly");
                        }
                    }
                    othis.addClass(DANGER);
                    return stop = true;
                }
            }
        });
        if (stop) return false;
        //返回序列化表单元素， JSON 数据结构数据。
        return true;
    };

    $('#cancel').on('click',function () {
        currentIndex = parent.layer.getFrameIndex(window.name);//获取当前窗体索引
        window.parent.layer.close(currentIndex);//执行关闭
    });
});